import React, { Component } from 'react';
import {Text, View, Image, TextInput, TouchableOpacity, StyleSheet, WebView, Platform} from 'react-native';
import { base } from "../../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import SegmentedControlTab from "react-native-segmented-control-tab";
import CheckBox from "react-native-check-box";
import ReactNativePickerSelect from "react-native-picker-select";
import Toast, {DURATION} from 'react-native-easy-toast'
const md5 = require('md5')
import { API } from "../../../api";
import Loading from '../../../components/loading/index'
import { DeviceStorage } from "../../../utils/DeviceStorage";
import { login } from "../../../utils/login";
import {i18n} from "../../../utils/locales/i18n";
import {EMAIL_REG_EXP, geetestURL, PASS_REGEXP, PHONE_REGEXP_HK, PHONE_REGEXP_ZH} from "../../../config";

type Props = {};
export default class Forgot extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('i189'),
            headerStyle: {
            },
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    };
    constructor() {
        super()
        this.state = {
            phoneNumber: '',
            mail: '',
            // 手机/邮箱注册
            selectedIndex: 0,
            // 验证码
            verifyCode: '',
            // 密码
            password: '',
            // 确认密码
            verifyPassword: '',
            geetestVisible: false,
            // 区号
            district: '+86',
            isChecked: true,
            username: '',
            // 已发送标志位
            isSend: false,
            // 重新发送倒数
            second: 60,
            modalVisible: false,
            currentToastInfo: ''
        }
    }
    // 标签切换
    changeTab = (index) => {
        this.setState({
            selectedIndex: index
        })
    }
    // 获取验证码
    getVerifyCode = () => {
        if (this.state.phoneNumber === '' && this.state.mail === '') {
            this.refs.toast.show(i18n.t('i190'))
            return
        }
        if (this.state.selectedIndex == 0) {
            if ((this.state.district === '+86' && !PHONE_REGEXP_ZH.test(this.state.phoneNumber)) || (this.state.district === '+852' && !PHONE_REGEXP_HK.test(this.state.phoneNumber))) {
                this.refs.toast.show(i18n.t('i241'))
                return
            }
        } else {
            if (!EMAIL_REG_EXP.test(this.state.mail)) {
                this.refs.toast.show(i18n.t('i241'))
                return
            }
        }
        this.setState({
            geetestVisible: true
        })
    }
    // webview加载失败处理
    onGeetestError = () => {
        this.setState({
            geetestVisible: false
        })
        alert('Geetest faild!')
    }
    // 处理极验返回的消息
    handleGeetestMessage = (e) => {
        e.persist();
        if (e.nativeEvent.data === 'send') {
            // 成功发送，隐藏webview
            setTimeout(() => {
                this.setState({
                    geetestVisible: false,
                    isSend: true
                })
                // 重新发送倒计时
                const timer = setInterval(() => {
                    this.setState({
                        second: this.state.second - 1
                    })
                    if (this.state.second <= 0) {
                        clearInterval(timer)
                        this.setState({
                            second: 60,
                            isSend: false
                        })
                    }
                }, 1000)
            }, 0)
        }
    }
    // 向极验webview 发送数据
    sendMessageToGeetest = () => {
        // type: 1注册 2绑定 3设置 4重置登陆密码 5重置资金密码 6提币验证码
        let options
        if (this.state.selectedIndex === 0) {
            options = {
                to: this.state.district + this.state.phoneNumber,
                type: 4
            }
        } else {
            // 邮箱
            options = {
                to: this.state.mail,
                type: 4
            }
        }
        this.refs.webview.postMessage(JSON.stringify(options))
    }
    // 手机注册
    doPhoneRegist = async () => {
        // {
        //     "key": "189321541652"
        //     "password":"ec05026a77a21fbd9929050f0070de01",
        //     "captcha":"769345"
        // }
        if (this.state.district === '' ||
            this.state.phoneNumber === '' ||
            this.state.verifyCode === '' ||
            this.state.password === '' ||
            this.state.verifyPassword === ''
        ) {
            this.refs.toast.show(i18n.t('plz_cpl'));
            return
        }

	    if (!PASS_REGEXP.test(this.state.password)) {
		    this.refs.toast.show(i18n.t('i240'));
		    return
	    }
        if (this.state.password != this.state.verifyPassword) {
            this.refs.toast.show(i18n.t('info28'));
            return
        }
        this.setState({
            modalVisible: true
        })
        const reqData = {
            key: this.state.phoneNumber,
            password: md5(md5(this.state.password)),
            captcha: this.state.verifyCode
        }
        const res = await API._fetch('resetPassword', reqData)
        this.setState({
            modalVisible: false
        })
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            this.props.navigation.goBack()
        } else {
            this.setState({
                modalVisible: false
            }, () => {
                this.refs.toast.show(res.msg || i18n.t('o_defeat'))
            })

        }

    }

    // 邮箱注册
    doEmailRegister = async () => {
        if (
            this.state.mail === '' ||
            this.state.verifyCode === '' ||
            this.state.password === '' ||
            this.state.verifyPassword === ''
        ) {
            this.refs.toast.show(i18n.t('plz_cpl'));
            return
        }
	    if (!PASS_REGEXP.test(this.state.password)) {
		    this.refs.toast.show(i18n.t('i240'));
		    return
	    }
        if (this.state.password != this.state.verifyPassword) {
            this.refs.toast.show(i18n.t('info28'));
            return
        }
        this.setState({
            modalVisible: true
        })
        const reqData = {
            key: this.state.mail,
            password: md5(md5(this.state.password)),
            captcha: this.state.verifyCode
        }
        const res = await API._fetch('resetPassword', reqData)
        this.setState({
            modalVisible: false
        })
        if (res.code === 10000) {
            this.refs.toast.show(res.msg || i18n.t('o_success'))
            this.props.navigation.goBack()
        } else {
            this.setState({
                modalVisible: false
            }, () => {
                this.refs.toast.show(res.msg || i18n.t('o_defeat'))
            })

        }
    }

    render() {
        return (
            <View style={[base.bg_white, base.flex_1, { position: 'relative' }]}>
                { this.state.modalVisible ? (
                    <Loading
                        info={this.state.currentToastInfo}
                    />) : null }
                {/*极验验证 */}
                { this.state.geetestVisible ? (
                    <View style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 999 }}>
                        <WebView
                            ref={'webview'}
                            onMessage={ msg => this.handleGeetestMessage(msg)}
                            onLoad={this.sendMessageToGeetest}
                            bounces={false}
                            javaScriptEnabled={true}
                            onError={this.onGeetestError}
                            style={{ flex: 1 }}
                            // source={require('../../../pages/geetest.html')}
                            source={{uri: geetestURL}}
                        />
                    </View>
                ) : null}
                {/*navigation*/}
                <View style={{ height: 100 }}>
                    <View style={{ flex:1, justifyContent: 'center', alignItems: 'center' }}>
                        <View style={{width: '50%'}}>
                            <SegmentedControlTab
                                values={[i18n.t('i191'), i18n.t('i192')]}
                                selectedIndex={this.state.selectedIndex}
                                tabStyle={{backgroundColor: '#fff', borderColor: '#ff7706', paddingVertical: 7 }}
                                activeTabStyle={{backgroundColor: '#ff7706'}}
                                tabTextStyle={{color: '#ff7706', fontSize: 16}}
                                activeTabTextStyle={{color: '#fff'}}
                                onTabPress={this.changeTab}
                            />
                        </View>
                    </View>
                </View>
                { this.state.selectedIndex === 0 ? (
                    <View style={[base.flex_1]}>
                        <View style={{paddingHorizontal: 15}}>
                            <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}>
                                    <Text style={{ fontSize: 16 }}>{i18n.t('i193')}</Text>
                                </View>
                                <View style={[base.flex_1, base.flex_row_between]}>
                                    <View style={[base.flex_row_start, base.flex_1, { marginVertical: 5, height: 40, borderRadius: 5, borderRightWidth: 0, borderTopRightRadius: 0, borderBottomRightRadius: 0, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                        <TextInput
                                            style={[base.color_gray]}
                                            value={this.state.phoneNumber}
                                            onChangeText={(text) => this.setState({phoneNumber: text})}
                                            placeholder={i18n.t('i194')}
                                        />
                                    </View>
                                    <View style={{width: 90}}>
                                        <View style={{position: 'relative', width: '100%', borderWidth: Platform.OS === 'ios' ? 0 : 0.5, borderColor: '#d2d2d2', borderRadius: 5, borderBottomLeftRadius: 0, borderTopLeftRadius: 0, height: 40 }}>
                                            <ReactNativePickerSelect
                                                style={{...pickerSelectStyles}}
                                                items={[
                                                    { label: '+86', value: '+86' },
                                                    { label: '+852', value: '+852' }
                                                ]}
                                                value={this.state.district}
                                                hideIcon={true}
                                                onValueChange={(district) => {this.setState({district})}}
                                            />
                                            <Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: '20%'}} source={require('@images/mine/icon_triangle.png')}/>
                                            {Platform.OS === 'ios' ? null : (
	                                            <View style={{ width: 200, height: 5, backgroundColor: '#fff', position: 'absolute', bottom: -6, right: 0 }}></View>
                                            )}
                                        </View>
                                    </View>
                                </View>
                            </View>
                            <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                <View style={[base.flex_row_between, {width: 90, paddingHorizontal: 5, paddingRight: 15}]}/>
                                <View style={[base.flex_1]}>
                                    <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingLeft: 15 }]}>
                                        <View style={[base.flex_1, { borderRightWidth: 0.5, borderRightColor: '#d2d2d2' }]}>
                                            <TextInput
                                                style={[base.color_gray, base.flex_1]}
                                                value={this.state.verifyCode}
                                                onChangeText={(text) => this.setState({verifyCode: text})}
                                                placeholder={i18n.t('i195')}
                                            />
                                        </View>
                                        { !this.state.isSend ?
                                            (<TouchableOpacity onPress={this.getVerifyCode} style={[base.flex_row_center, {height: '100%', width: 90}]}>
                                            <Text style={[base.color_orange]}>{i18n.t('i196')}</Text>
                                        </TouchableOpacity>) :
                                            (<TouchableOpacity style={[base.flex_row_center, {height: '100%', width: 90}]}>
                                                <Text style={[base.color_gray, { fontSize: 12 }]}><Text>{ this.state.second }</Text>s</Text>
                                            </TouchableOpacity>) }

                                    </View>
                                </View>
                            </View>
                            <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}>
                                    <Text style={{ fontSize: 16 }}>{i18n.t('i197')}</Text>
                                    {/*<Text style={{ fontSize: 16 }}>密</Text>*/}
                                    {/*<Text style={{ fontSize: 16 }}>码</Text>*/}
                                </View>
                                <View style={[base.flex_1]}>
                                    <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                        <TextInput
                                            style={[base.color_gray]}
                                            value={this.state.password}
                                            onChangeText={(text) => this.setState({password: text})}
                                            placeholder={i18n.t('i198')}
                                            secureTextEntry={true}
                                        />
                                    </View>
                                </View>
                            </View>
                            <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                                <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}>
                                    <Text style={{ fontSize: 16 }}>{i18n.t('i199')}</Text>
                                    {/*<Text style={{ fontSize: 16 }}>认</Text>*/}
                                    {/*<Text style={{ fontSize: 16 }}>密</Text>*/}
                                    {/*<Text style={{ fontSize: 16 }}>码</Text>*/}
                                </View>
                                <View style={[base.flex_1]}>
                                    <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                        <TextInput
                                            style={[base.color_gray]}
                                            value={this.state.verifyPassword}
                                            onChangeText={(text) => this.setState({verifyPassword: text})}
                                            placeholder={i18n.t('i198')}
                                            secureTextEntry={true}
                                        />
                                    </View>
                                </View>
                            </View>

                        </View>
                        <View style={[base.flex_1, base.flex_col_center, {paddingHorizontal: 20, paddingBottom: '15%'}]}>
                            <TouchableOpacity style={{width: '100%'}} onPress={this.doPhoneRegist}>
                                <LinearGradient
                                    start={{x: 0, y: 0}}
                                    end={{x: 1, y: 1}}
                                    colors={['#feac1c', '#ff7506']}
                                    style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                                >
                                    <Text style={{color: '#fff', fontSize: 16}}>{i18n.t('submit')}</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                    </View>
                    ) : (<View style={[base.flex_1]}>
                    <View style={{paddingHorizontal: 15}}>
                        <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                            <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}><Text style={{ fontSize: 16 }}>{i18n.t('i200')}</Text></View>
                            <View style={[base.flex_1]}>
                                <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                    <TextInput
                                        style={[base.color_gray]}
                                        value={this.state.mail}
                                        onChangeText={(text) => this.setState({mail: text})}
                                        placeholder={i18n.t('i201')}
                                    />
                                </View>
                            </View>
                        </View>
                        <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                            <View style={[base.flex_row_between, {width: 90, paddingHorizontal: 5, paddingRight: 15}]}/>
                            <View style={[base.flex_1]}>
                                <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingLeft: 15 }]}>
                                    <TextInput
                                        style={[base.color_gray, base.flex_1, {borderRightColor: '#e5e5e5', borderRightWidth: 0.5}]}
                                        value={this.state.verifyCode}
                                        onChangeText={(text) => this.setState({verifyCode: text})}
                                        placeholder={i18n.t('i202')}
                                    />
                                    { !this.state.isSend ?
                                        (<TouchableOpacity onPress={this.getVerifyCode} style={[base.flex_row_center, {height: '100%', width: 90}]}>
                                            <Text style={[base.color_orange]}>{i18n.t('i196')}</Text>
                                        </TouchableOpacity>) :
                                        (<TouchableOpacity style={[base.flex_row_center, {height: '100%', width: 90}]}>
                                            <Text style={[base.color_gray, { fontSize: 12 }]}><Text>{ this.state.second }</Text>s</Text>
                                        </TouchableOpacity>) }
                                </View>
                            </View>
                        </View>
                        <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                            <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}>
                                <Text style={{ fontSize: 16 }}>{i18n.t('i197')}</Text>
                                {/*<Text style={{ fontSize: 16 }}>密</Text>*/}
                                {/*<Text style={{ fontSize: 16 }}>码</Text>*/}
                            </View>
                            <View style={[base.flex_1]}>
                                <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                    <TextInput
                                        style={[base.color_gray]}
                                        value={this.state.password}
                                        onChangeText={(text) => this.setState({password: text})}
                                        placeholder={i18n.t('i198')}
                                        secureTextEntry={true}
                                    />
                                </View>
                            </View>
                        </View>
                        <View style={[base.flex_row_start, { paddingVertical: 5 }]}>
                            <View style={[base.flex_row_between, { width: 90, paddingHorizontal: 5, paddingRight: 15 }]}>
                                <Text style={{ fontSize: 16 }}>{i18n.t('i199')}</Text>
                                {/*<Text style={{ fontSize: 16 }}>认</Text>*/}
                                {/*<Text style={{ fontSize: 16 }}>密</Text>*/}
                                {/*<Text style={{ fontSize: 16 }}>码</Text>*/}
                            </View>
                            <View style={[base.flex_1]}>
                                <View style={[base.flex_row_between, { marginVertical: 5, height: 40, width: '100%', borderRadius: 5, borderWidth: 0.5, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                                    <TextInput
                                        style={[base.color_gray]}
                                        value={this.state.verifyPassword}
                                        onChangeText={(text) => this.setState({verifyPassword: text})}
                                        placeholder={i18n.t('i198')}
                                        secureTextEntry={true}
                                    />
                                </View>
                            </View>
                        </View>

                    </View>
                    <View style={[base.flex_1, base.flex_col_center, {paddingHorizontal: 20, paddingBottom: '15%'}]}>
                        <TouchableOpacity style={{width: '100%'}} onPress={this.doEmailRegister}>
                            <LinearGradient
                                start={{x: 0, y: 0}}
                                end={{x: 1, y: 1}}
                                colors={['#feac1c', '#ff7506']}
                                style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                            >
                                <Text style={{color: '#fff', fontSize: 16}}>{i18n.t('submit')}</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </View>)}

                {/*toast*/}
                <Toast ref="toast" position='bottom' positionValue={200}/>
            </View>
        );
    }

}

const pickerSelectStyles = StyleSheet.create({
    inputIOS: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 10,
        borderWidth: 0.5,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        borderBottomLeftRadius: 0,
        borderTopLeftRadius: 0,
        backgroundColor: 'white',
        color: '#ff7606',
        marginVertical: 5
    },
    inputAndroid: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 30,
        width: 100,
        padding: 0,
        margin: 0,
	    // paddingHorizontal: 10,
        borderWidth: 0.5,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        borderBottomLeftRadius: 0,
        borderTopLeftRadius: 0,
        backgroundColor: 'white',
        color: '#ff7606',
        marginVertical: 5
    },
});
